package ltd.dujiabao.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.springcloud.entities.CommonResult;
import ltd.dujiabao.springcloud.handler.BlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : DuJiabao
 * @Project : springcloud
 * @Time : 2021/5/26 16:52
 * @Desc :
 */
@RestController
@Slf4j
public class RateLimitController {
  @GetMapping("/testHandler")
  //@SentinelResource(value = "testHandler", blockHandler = "blockHandler")
  @SentinelResource(value = "testHandler", blockHandler = "handleException1", blockHandlerClass = BlockHandler.class)
  public CommonResult<Object> testHandler() {
    return new CommonResult<>(CommonResult.SUCCESS, "testHandler Success");
  }

  @GetMapping("/testTimeOutHandler")
  @SentinelResource(value = "testTimeOutHandler", blockHandler = "blockHandler")
  public CommonResult<Object> testTimeOutHandler() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return new CommonResult<>(CommonResult.SUCCESS, "testTimeOutHandler Success");
  }

  @SentinelResource(value = "testFallback", fallback = "exceptionFallback", exceptionsToIgnore = ArithmeticException.class)
  @GetMapping("/testFallback/{i}")
  public CommonResult<Object> testFallback(@PathVariable("i") Integer i) {
    log.info("接收到数据 i = " + i);
    System.out.println(10 / i);
    return new CommonResult<>(CommonResult.SUCCESS, "testFallback: 接收到数据了", i);
  }

  public CommonResult<Object> exceptionFallback(Integer i) {
    log.info("接收到数据 i = " + i);
    return new CommonResult<>(CommonResult.FAIlURE, "exceptionFallback: 接收到数据了", i);
  }

  public CommonResult<Object> blockHandler(BlockException exception) {
    return new CommonResult<>(CommonResult.FAIlURE, "blockHandler Failure");
  }
}
